using System;
using System.Collections.Generic;
using System.Text;
using PostSharp.Laos;

using Spring.Context.Support;
using Spring.Context;
using System.Diagnostics;
using System.Reflection;
using System.Web;

using B4ALL.Common;

namespace B4ALL.Cache.Standard
{

    public class StandardCacheService : ICacheHandler
    {

        #region props

        private IDataCacheManager cacheManager;

        public IDataCacheManager CacheManager
        {
            get { return cacheManager; }
            set { cacheManager = value; }
        }

        #endregion props

        #region ICacheHandler

        /// <summary>
        /// Tests if method returns value is already in cache. Otherwise, lets the method execute.
        /// </summary>
        /// <param name="eventArgs"></param>
        public HandlerBehavior OnEntry(MethodExecutionEventArgs eventArgs, OnMethodBoundaryAspect aspect)
        {
            Object result = null;

            String methodHash = GetMethodHash(eventArgs);
            result = cacheManager.Get(methodHash);

            if (result != null && (result.GetType() == ((MethodInfo)eventArgs.Method).ReturnType
                || result.GetType().GetInterface(((MethodInfo)eventArgs.Method).ReturnType.Name) != null
                || result.GetType().IsSubclassOf(((MethodInfo)eventArgs.Method).ReturnType)))
            {
                eventArgs.ReturnValue = result;
                eventArgs.FlowBehavior = FlowBehavior.Return;
                return HandlerBehavior.Break;
            }
            else
            {
                eventArgs.MethodExecutionTag = methodHash;
                return HandlerBehavior.Continue;
            }

            
        }

        /// <summary>
        /// Method return value is insert in cache manager
        /// </summary>
        /// <param name="eventArgs"></param>
        public HandlerBehavior OnSuccess(MethodExecutionEventArgs eventArgs, OnMethodBoundaryAspect aspect)
        {
            if (cacheManager != null && eventArgs.MethodExecutionTag != null)
            {
                lock (cacheManager)
                {
                    CacheContext cacheContext = Context.GetContext<CacheContext>();

                    Object result = cacheManager.Get((String)eventArgs.MethodExecutionTag);

                    if (result == null && cacheContext != null && cacheContext.Duration.HasValue)
                        cacheManager.Add((String)eventArgs.MethodExecutionTag, eventArgs.ReturnValue, cacheContext.Duration.Value);
                    else if (result == null)
                        cacheManager.Add((String)eventArgs.MethodExecutionTag, eventArgs.ReturnValue);
                    else if (cacheContext != null && cacheContext.Refresh.HasValue && cacheContext.Refresh.Value)
                        cacheManager.Refresh((String)eventArgs.MethodExecutionTag, eventArgs.ReturnValue);
                }
            }

            return HandlerBehavior.Break;
        }

        #endregion ICacheHandler

        /// <summary>
        /// Uniquely identifies a method at runtime
        /// </summary>
        /// <param name="eventArgs"></param>
        /// <returns></returns>
        private String GetMethodHash(MethodExecutionEventArgs eventArgs)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(eventArgs.Method.ReflectedType.FullName);

            sb.AppendFormat(":{0}", eventArgs.Method.Name);

            if (eventArgs.Instance != null)
            {
                sb.AppendFormat(":[instance:{0}]", eventArgs.Instance.ToString());
            }

            if (eventArgs.Method.IsGenericMethod)
            {
                foreach (Type t in eventArgs.Method.GetGenericArguments())
                {
                    sb.AppendFormat(":[{0}:{1}]", "generic", t.Name);
                }
            }

            object[] arguments = eventArgs.GetArguments();
            if (arguments != null)
            {
                foreach (Object param in arguments)
                {
                    if (param == null)
                        sb.AppendFormat(":[{0}:{1}]", "null", "null");
                    else if (param.GetType().GetInterface("icollection", true) != null)
                    {
                        System.Collections.ICollection col = (System.Collections.ICollection)param;
                        sb.AppendFormat(":[{0}:{1}]", param.GetType().Name, GetCollectionValues(col));
                    }
                    else
                        sb.AppendFormat(":[{0}:{1}]", param.GetType().Name, param.ToString());

                }
            }

            return sb.ToString();
        }

        private static String GetCollectionValues(System.Collections.ICollection col)
        {
            StringBuilder str = new StringBuilder();

            foreach (Object obj in col)
            {
                str.Append(obj.ToString());
                str.Append("^-^");
            }

            return str.ToString();
        }

    }
}
